﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using InstaSharp.Models;

namespace BlogsAPI.GeoLocation
{
    /// <summary>
    /// Ответ по запросу с координатами
    /// </summary>
    public struct GeoResult
    {
        /// <summary>
        /// Имя города
        /// </summary>
        public string City;
        /// <summary>
        /// Имя страны
        /// </summary>
        public string CountryCode;
    }

    public static class GeoMix
    {
        private static int currentId = 0;

        /// <summary>
        /// Сервисы
        /// </summary>
        private static List<IGeoCoder> Services = new List<IGeoCoder>
        { 
            new GeoYandex(),
            new GeoGoogle()
        };

        /// <summary>
        /// Получение координат по адресу
        /// </summary>
        /// <param name="address">текстовое описание места</param>
        /// <param name="lang">язык результата</param>
        /// <returns>Координаты</returns>
        public static Location GetCoordsFromAddress(string address, CultureInfo lang = null)
        {
            var first = Services[currentId];
            var ret = first.GetCoordsFromAddress(address, lang);
            if (ret == null)
            {
                currentId = (++currentId)%Services.Count; //переключаем с 1 на 2
                ret = Services[currentId].GetCoordsFromAddress(address, lang);
            }
            return ret;
        }

        /// <summary>
        /// Получение имени города по координатам
        /// </summary>
        /// <param name="lat">широта</param>
        /// <param name="lng">долгота</param>
        /// <param name="lang">язык результата</param>
        /// <returns>Имя города</returns>
        public static GeoResult GetCityFromCoords(double lat, double lng, CultureInfo lang = null)
        {
            var first = Services[currentId];
            var ret = first.GetCityFromCoords(lat,lng, lang);
            if (String.IsNullOrEmpty(ret.City))
            {
                currentId = (++currentId) % Services.Count; //переключаем с 1 на 2
                ret = Services[currentId].GetCityFromCoords(lat, lng, lang);
            }
            return ret;
        }
    }
}
